package com.timer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.mgr.DriveRecordMgr;
import com.player.WorldMgr;
import com.qy.db.pool.DBPoolMgr;
import com.qy.util.LogUtil;

/**
 * 定时任务管理类
 * @author lym
 *
 */
public class TimerTaskMgr {

	// 最小时间隔1分钟
	protected static final int MINTIME = 1000 * 60;

	private static Timer scanTimer;
	private static Timer saveUserDataTimer;
	private static Timer saveLogDataTimer;
	
	public static boolean init() {
		// 设置启动时间
		Date beginDate = new Date();
		scanTimer = new Timer("ScanTimer");

		// 每天00:00:01重置数据
		try {
			
			// 保存用户数据
			saveUserDataTimer = new Timer("SaveUserDataTimer");
			TimerTask saveUserData = new SaveUserData();
			saveUserDataTimer.schedule(saveUserData, beginDate, MINTIME * 5);

			// 保存日志数据
			saveLogDataTimer = new Timer("SaveLogDataTimer");
			TimerTask saveLogData = new SaveLogData();
			saveLogDataTimer.schedule(saveLogData, beginDate, MINTIME * 1);
		} catch (Exception e) {
			LogUtil.error("定时器 scanLastLogOutDate,scanFarmReset 异常", e);
		}

		// 检查DBPool是否正常
		TimerTask checkDBPool = new DBPool();
		scanTimer.schedule(checkDBPool, MINTIME * 3, MINTIME * 5);

		
		return true;
	}
}

abstract class Task extends TimerTask {
	private String name;

	public Task(String name) {
		this.name = "定时器任务-" + name;
	}

	@Override
	public void run() {
		try {
			exec();
		} catch (Exception e) {
			LogUtil.error(name + "错误", e);
		}
	}

	public abstract void exec();

}

/**
 * 保持用户数据
 */
class SaveUserData extends Task {

	public SaveUserData() {
		super("保存数据");
	}

	@Override
	public void exec() {
		WorldMgr.saveData();
	}
}

/**
 * 保持日志数据
 */
class SaveLogData extends Task {
	
	public SaveLogData() {
		super("日志数据");
	}
	
	@Override
	public void exec() {
		DriveRecordMgr.save();
	}
}


/**
 * 检查连接池状态
 *
 */
class DBPool extends Task {

	public DBPool() {
		super("检查连接池状态");
	}

	@Override
	public void exec() {
		DBPoolMgr.checkConnectionPool(true, true, true);
	}
}




